#include "idledetector.h"
#include <QCursor>
#include <QDebug>
#include <QMouseEvent>
#include <QFont>

/* Create and start the idle detector.
 * @param idleSeconds - Number of seconds before emitting the idle signal
 */
IdleDetector::IdleDetector(int idleSeconds, QWidget* parent) : userIdle(false), enabled(true), measurementsLeft(10) {
	setParent(parent);
	setText(QString::number(measurementsLeft));
	setToolTip("Number of idle minutes left before music is stopped");
	startTimer(idleSeconds*100);  // we divide the timeout by 10 to reduce the chance of false detections to basically zero.
	lastMousePosition = QCursor::pos();
	QFont font;
	font.setPointSize(font.pointSize()+4);
	font.setBold(true);
	setFont(font);
}

void IdleDetector::timerEvent(QTimerEvent*) {
	if(enabled) {
		if((lastMousePosition-QCursor::pos()).manhattanLength() < 3) // if we haven't moved since our last measurement
			measurementsLeft = qMax(measurementsLeft-1, 0);
		else { // we have moved, reset the counter
			measurementsLeft = 10;
			userIdle = false;
		}
		lastMousePosition = QCursor::pos();

		setText(QString::number(measurementsLeft));
		if(!measurementsLeft) {  // no measurements left
			if(!userIdle) {// only emit the signal if we aren't already idle
				userIdle = true;
				emit(idle());
			}
		}
	}
}

void IdleDetector::setEnabled(bool on) {
	enabled = on;
	if(enabled) {
		measurementsLeft = 10;
		setText(QString::number(measurementsLeft));
	}
	else
		setText(QChar(0x221E));
}

void IdleDetector::mousePressEvent(QMouseEvent* event) {
	if(event->button() == Qt::LeftButton)
		setEnabled(!enabled);
}
